package com.reyco1.services.youtube
{
	import com.reyco1.core.LoginConstants;
	import com.reyco1.data.Collection;
	import com.reyco1.events.SmartEventDispatcher;
	import com.reyco1.loading.DataLoader;
	
	import flash.events.Event;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	import flash.system.LoaderContext;
	
	public class YoutubeSearch extends SmartEventDispatcher
	{
		private var dataLoader:DataLoader;
		private var currentQuery:String;
		
		private var _videos:Collection;
		private var _id:String;
		
		public function YoutubeSearch(classIdentifyer:String = null)
		{
			super();
			_id = classIdentifyer;
		}
		
		public function search(query:String, amount:Number = 15, orderBy:String = "published"):void
		{
			currentQuery = query;
			
			var variables:URLVariables  = new URLVariables();
			variables.q	  		     	= currentQuery;
			variables.key 		     	= LoginConstants.YOUTUBE_API_KEY;
			variables.format 		 	= 1;
			variables.orderby			= orderBy;
			variables.v					= 2
			variables["max-results"] 	= amount;
			
			var request:URLRequest = new URLRequest(LoginConstants.YOUTUBE_ENDPOINT);
			request.data = variables;
			
			dataLoader = new DataLoader(request, {onComplete:handleGotVideoData});
			dataLoader.load();
		}
		
		private function handleGotVideoData(content:*):void
		{
			_videos = new Collection();
			
			var responseXML:XML   = XML(content);
			var ns:Namespace 	  = responseXML.namespace("");
			var gd:Namespace 	  = responseXML.namespace("gd");
			var media:Namespace   = responseXML.namespace("media");
			var yt:Namespace 	  = responseXML.namespace("yt");			
			var videoList:XMLList = responseXML.ns::entry;
			
			var videoData:YoutubeVideoData;
			
			for each(var videoElement:XML in videoList)
			{
				videoData 				= new YoutubeVideoData();
				videoData.title 		= videoElement.ns::title;
				videoData.published 	= videoElement.ns::published;
				videoData.rating 		= int(videoElement.gd::rating.@average);
				videoData.description 	= videoElement.media::group.media::description;
				videoData.keywords 		= videoElement.media::group.media::keywords;
				videoData.category 		= videoElement.media::group.media::category;
				videoData.thumbnail 	= videoElement.media::group.media::thumbnail[0].@url;
				videoData.duration 		= Number(videoElement.media::group.yt::duration.@seconds);
				videoData.id			= videoElement.media::group.yt::videoid; 
				videoData.url			= videoElement.media::group.media::content.(String(@url).substr(0,4) == "http").@url;
				
				if(videoData.id)
				{
					_videos.addItem(videoData);  
				} 
			}
			
			if(dataLoader)
			{
				dataLoader.destroy();
				dataLoader = null;
			}
			
			dispatchEvent(new Event(Event.COMPLETE));
		}

		public function get videos():Collection
		{
			return _videos;
		}

	}
}